<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <!-- <span>卡片名称</span> -->
      <el-button
        icon="el-icon-plus"
        type="primary"
        size="middle"
        @click="dialogVisible = true"
        >添加品牌</el-button
      >
    </div>
    <!-- 品牌数据列表 -->
    <el-table
      class="mb-10"
      :data="trademarkList"
      :row-style="obj"
      border
      style="width: 100%"
    >
      <el-table-column label="序号" type="index" width="180" align="center">
      </el-table-column>
      <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
      <el-table-column label="品牌LOGO" prop="logoUrl">
        <template #default="{ row, $index }">
          <img
            style="width: 80px; height: 80px"
            :src="row.logoUrl"
            :id="$index"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            icon="el-icon-edit-outline"
            type="warning"
            size="small"
            @click="editTM(row)"
            >编辑</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="danger"
            size="small"
            @click="deleteTM(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 6, 9]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
    >
    </el-pagination>

    <!-- 添加与编辑品牌的对话框 -->
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :model="tmForm"
        :rules="rules"
        ref="tmForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmForm.tmName" style="width: 65%"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 图片上传 -->
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span>图片只能是JPG格式并且图片的大小不能超过2MB！！</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSave('tmForm')">取 消</el-button>
        <el-button type="primary" @click="onSave('tmForm')">保 存</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import trademarkApi from "@/api/trademark";
import { cloneDeep } from "lodash";
export default {
  name: "Trademark",
  data() {
    return {
      obj: {
        height: "100px",
      },
      // 存储分页器相关数据
      page: 1,
      limit: 3,
      total: 10,
      // 存储品牌列表数据
      trademarkList: [],
      // 控制弹窗的展示与隐藏
      dialogVisible: false,
      // 存储form表单中的数据
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      // 表单校验
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOGO", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 分页器相关的回调函数
    handleCurrentChange(val) {
      // console.log('改变当前的页码',val);
      this.page = val;
      this.getPage();
    },
    handleSizeChange(val) {
      // console.log('改变每页显示的额条数',val);
      this.limit = val;
      this.getPage();
    },
    // 获取品牌数据列表
    async getPage() {
      try {
        let result = await trademarkApi.getPage(this.page, this.limit);
        // console.log("获取到的品牌数据", result);
        // 存储获取到的品牌列表数据
        this.trademarkList = result.data.records;
        // 存储数据的总条数
        this.total = result.data.total;
      } catch (error) {
        // console.log("获取数据失败，请重试");
        this.$message.error("获取数据失败，请重试");
      }
    },

    // 图片上传的相关回调
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传品牌LOGO图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传品牌LOGO图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 保存
    async onSave(formName) {
      console.log(this.tmForm);

      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // alert('submit!');
          // 点击保存时调用api中的方法发送请求
          try {
            // 点击保存之后看品牌是否存在id,若存在id说明是在修改品牌，否则添加
            if (this.tmForm.id) {
              await trademarkApi.editTrademark(this.tmForm);
            } else {
              await trademarkApi.addTrademark(this.tmForm);
            }
            // console.log(result);
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.tmForm = {
              tmName: "",
              logoUrl: "",
            };
            this.getPage();
          } catch (error) {
            this.$message.error("保存失败，请重试");
          }
        }
      });
    },
    // 取消的回调
    cancelSave(formName) {
      this.dialogVisible = false;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
      this.$refs[formName].resetFields();
    },

    // 编辑商品的回调
    async editTM(row) {
      this.dialogVisible = true;
      this.tmForm = cloneDeep(row);
    },

    // 删除商品的的回调
    async deleteTM(row) {
      this.$confirm(`确认删除[${row.tmName}]这个品牌么?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await trademarkApi.deleteTrademark(row.id);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.page = 1
            this.getPage();
          } catch (error) {
            this.$message.error("删除失败，请重试");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted() {
    this.getPage();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  widows: 1285px;
  margin: 20px;
}

/* 品牌图标上传相关样式 */
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>